#include "dyntablemodel.h"
#include <QJsonObject>
#include <QDebug>

//TODO: save changes back to ust

#define INIT(k) d = new DynTableData; d->key=k; _data.push_back(d);

DynTableModel::DynTableModel()
{
    DynTableData* d;
    INIT("DYN");
    INIT("PIT");
    INIT("PHO");
}

int DynTableModel::rowCount(const QModelIndex &parent) const
{
    (void) parent;
    return _data.size();
}

int DynTableModel::columnCount(const QModelIndex &parent) const
{
    (void) parent;
    return 2;
}

QVariant DynTableModel::data(const QModelIndex &index, int role) const
{
    if(role==Qt::DisplayRole || role==Qt::EditRole)
    {
        int r = index.row();
        int c = index.column();
        if(c==0)
            return _data[r]->key;
        else
            return _data[r]->value;

    }
    return QVariant();
}

QVariant DynTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    //TODO -- implement header 1
    return QVariant();
}

Qt::ItemFlags DynTableModel::flags(const QModelIndex &index) const
{
    if (index.column() == 0)
        {
            return Qt::ItemIsEnabled | Qt::ItemNeverHasChildren;
        }
        else
        {
            return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemNeverHasChildren;
        }
}


bool DynTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    int r = index.row();
    int c = index.column();
    if(c==1)
    {
        _data[r]->valueOrig = _data[r]->value;
        _data[r]->value = value.toString();
        _data[r]->updated = true;
        return true;
    }
    return false;
}

void DynTableModel::loadOne(quint64 sel1, QJsonObject o)
{
    for(int i=0;i<_data.size();i++)
    {
        auto d = _data[i];
        d->value = o[d->key].toString();
        d->valueOrig = d->value;
    }

    _sel1 = sel1;

    QModelIndex topLeft;
    QModelIndex bottomRight;
    emit dataChanged(topLeft,bottomRight);

}

void DynTableModel::reset()
{
    for(int i=0;i<_data.size();i++)
    {
        auto d = _data[i];
        d->value = "";
        d->updated=false;
    }

    _sel1 = -1;

    QModelIndex topLeft;
    QModelIndex bottomRight;
    emit dataChanged(topLeft,bottomRight);

}

bool DynTableModel::hasChanges(QVector<quint64> sel)
{
    if(_sel1==-1) return false;
    if(sel.size()==1 && sel[0]==_sel1) return false;
    for(int i=0;i<_data.size();i++)
    {
        auto d = _data[i];
        if(d->updated)
            return true;
    }
    return false;

}

void DynTableModel::saveChanges()
{
    qtauEvent_NoteEffect::noteEffectVector changeset;
    qtauEvent_NoteEffect::noteEffectData change0;

    change0.id = _sel1;

    for(int i=0;i<_data.size();i++)
    {
        auto d = _data[i];
        if(d->updated)
            change0.kv[d->key]= d->value;
            change0.prevKv[d->key] = d->valueOrig;
     }

    changeset.push_back(change0);
    emit noteEffect(new qtauEvent_NoteEffect(changeset));
}
